<?php

namespace App\Service;

use App\Constants\ServerCode;
use App\Model\User;
use App\Service\Dao\UserDao;
use Hyperf\Context\ApplicationContext;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;
use function Hyperf\Support\env;

class UserService
{
    #[Inject]
    protected UserDao $user_dao;

    public function register($request){
        $account = $request['account'];
        $password = $request['password'];

        $get_user_where = [
            ['account','=',$account]
        ];

        $user_message = $this->user_dao->getUserFirst($get_user_where);

        if (!empty($user_message)){
            return ['status'=>false,'message'=>'该账号已经注册用户','code'=>ServerCode::ERROR_MESSAGE_INFO];
        }

        $sale = $this->sale();
        $password = md5($sale.$password);



        $data = [
            'user_name' => $account,
            'account' => $account,
            'password' => $password,
            'sale' => $sale,
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
        ];

        $insert  = $this->user_dao->insert($data);
        if ($insert){
            return ['status'=>true,'message'=>'注册成功','code'=>ServerCode::SUCCESS_CODE];
        }
        return ['status'=>false,'message'=>'注册失败','code'=>ServerCode::ERROR_REQUEST_FAIL];

    }

    public function sale(){
        $str = md5(time());
        return $str;
    }


    public function login($request){
        $account = $request['account'];
        $password = $request['password'];

        $get_user_where = [
            ['account','=',$account]
        ];

        $user_message = $this->user_dao->getUserFirst($get_user_where);
        if (empty($user_message)){
            return ['status'=>false,'message'=>'账号不存在','code'=>ServerCode::ERROR_USER_VALIDATE];
        }

        if ($user_message['password'] != md5($user_message['sale'].$password)){
            return ['status'=>false,'message'=>'密码错误','code'=>ServerCode::ERROR_USER_VALIDATE];
        }

        $user_id = $user_message['user_id'];


        $sale = $this->sale();
        $sessionKey = md5($user_id."USER".$sale);

        $container = ApplicationContext::getContainer();
        $redis = $container->get(Redis::class);



        //删除旧的登录sessionKey
        if ($redis->exists('user_sessionKey_'.$user_id)){
            $redis->del('user_sessionKey_'.$user_id);
        }


        $login_time = (int)env('LOGIN_TIME');


        $redis->set("user_sessionKey_".$user_id,$sessionKey,$login_time);

        //保存用户id
        $redis->set($sessionKey,$user_id,$login_time);

        //更新用户信息
        $redis->set('user_info_'.$user_id,json_encode($user_message),$login_time);

        $user_message['sessionKey'] = $sessionKey;

        return ['status'=>true,'message'=>$user_message,'code'=>ServerCode::SUCCESS_CODE];


    }

}